package controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Game;
import model.User;
import model.User.UserStatus;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import snake.Player;
import utils.LoggedUser;
import utils.LoggedUser.UserType;
import utils.UserSession;
import dao.UserDao;

@Controller
public class UserController
{
	@RequestMapping("/")
	public String getIndex(HttpServletRequest request)
	{
		if(LoggedUser.isLogged(request.getSession()))
		{
			return "mainPage";
		}
		return "index";
	}

	@RequestMapping(value = "login.do", method = RequestMethod.POST)
	public String processCredentials(HttpServletRequest request, HttpServletResponse response)
	{
		final String badLogin = "badLogin";
		String userName = (String) request.getParameter("username");
		String password = (String) request.getParameter("password");
		String message = "";
		UserStatus status = UserStatus.online;
		HttpSession session = request.getSession();

		if (!userName.equals("") && !password.equals(""))
		{
			User user = UserDao.getByUsernameAndPassword(userName, password);

			if (user == null)
			{
				message = "Invalid credentials";
			} 
			else
			{
				user.setStatus(status);
				// trebuie de modificat statusul din BD

				LoggedUser lUser = new LoggedUser(user, UserType.registered);
				LoggedUser.setUser(session, lUser);
				
				List<UserSession> userSessions = (List<UserSession>) request.getServletContext().getAttribute("userSessions");
				
				if(userSessions == null)
				{
					userSessions = new ArrayList<UserSession>();
					request.getServletContext().setAttribute("userSessions", userSessions);				
				}
				
				for(int i = 0; i < userSessions.size(); i++)
				{
					if(userSessions.get(i).getUser().getUsername().equals(lUser.getUsername()))
					{		
						
						userSessions.get(i).getSession().invalidate();
						userSessions.remove(i);
					}
				}
				userSessions.add(new UserSession(lUser, session));
							
				return "mainPage";
			}
		} 
		else
		{
			message = "Login or Password is empty";
		}
		session.setAttribute(badLogin, message);
		return "index"; 
	}

	@RequestMapping("/register.do")
	public String registerUser()
	{
		return "register";
	}

	@RequestMapping("/registerUser.do")
	public String loginGuest(HttpServletRequest request)
	{
		String username = request.getParameter("username");
		String password1 = request.getParameter("password1");
		String password2 = request.getParameter("password2");

		if (password1.equals(password2) && !password1.equals("")
				&& !username.equals(""))
		{
			UserDao.addUser(username, password1);
			return "index";
		} 
		else
			return "register";
	}

	@RequestMapping("/loginGuest.do")
	public String loginInAGuest(HttpServletRequest request)
	{
		HttpSession session = request.getSession();
		Random r = new Random();
		int low = 10;
		int high = 100;
		int rand = r.nextInt(high - low) + low;

		String guestName = "Guest" + rand;

		session.setAttribute("Guest", guestName);

		return "mainPage";
	}
	
	@RequestMapping("/logOut.do")
	public String logOut(HttpServletRequest request)
	{
		Integer id=(Integer) request.getSession().getAttribute("gameId");
		if(id!=null)
		{
			List<Game> games=(List<Game>) request.getServletContext().getAttribute("games");
			
			if (games.size()>0)
			{			
				List<User> playerList=games.get(id).getPlayerList();
				
				for (int i=0;i<playerList.size();i++)
				{
					
					if (playerList.get(i)==LoggedUser.getUser(request.getSession()))
					{
						if(i==0)
						{
							games.remove((int)id);					
						}
						else
						{
							playerList.remove(i);
						}
					}
					
				}	
			}

		}
		
		List<UserSession> userSessions = (List<UserSession>) request.getServletContext().getAttribute("userSessions");
		
		
		LoggedUser lUser=LoggedUser.getUser(request.getSession());
		
		for(int i = 0; i < userSessions.size(); i++)
		{
			if(userSessions.get(i).getUser().getUsername().equals(lUser.getUsername()))
			{		
				userSessions.remove(i);
			}
		}
		
		request.getSession().invalidate();
		return "index";
	}
	
	@RequestMapping("/goToMainPage")
	public String goToMainPage(HttpServletRequest request)
	{
		if(LoggedUser.isLogged(request.getSession()))
		{
			return "mainPage";
		}
		
		return "index";
		
	}
	
}
